package com.yao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.dto.DictTypeDto;
import com.yao.sys.mapper.DictTypeMapper;
import com.yao.sys.mapper.sql.DictTypeWrapper;
import com.yao.sys.service.DictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 字典类型表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Service
@Slf4j
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictTypeDto> implements DictTypeService {

    // 字典类型code 规则：系统_TABLE_字段 例如：RO_GOODS_TYPE

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void add(DictTypeDto model) {
        // 检查重复项
        this.check(model.getCode());

        if (!this.save(model)) {
            throw new BusinessException("新增字典类型失败.");
        }

    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void modifyById(DictTypeDto model) {
        // 检查重复项
        this.check(model.getCode());

        if (!this.updateById(model)) {
            throw new BusinessException("更新字典类型失败.");
        }

    }

    private void check(String code) {
        Wrapper<DictTypeDto> query = DictTypeWrapper.byCode(code);
        boolean present = Optional.ofNullable(this.getOne(query)).isPresent();
        if (present) {
            throw new BusinessException("code重复");
        }
    }

}